package com.macro.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.dao.OrderProductStatDao;
import com.macro.mall.dao.UmsStoreDao;
import com.macro.mall.dto.*;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.service.UmsAdminCacheService;
import com.macro.mall.service.UmsAdminService;
import com.macro.mall.service.UmsStoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class UmsStoreServiceImpl implements UmsStoreService {

    @Autowired
    private UmsStoreMapper storeMapper;
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private UmsCheckInIntegrationMapper checkInMapper;
    @Autowired
    private UmsAdminService umsAdminService;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OrderProductStatDao statDao;
    @Autowired
    private UmsAdminRoleRelationMapper roleRelationMapper;
    @Autowired
    private UmsRoleMapper roleMapper;
    @Autowired
    private UmsAdminCacheService cacheService;
    @Autowired
    private UmsStoreDao umsStoreDao;
    @Autowired
    private UmsAdminCacheService redisService;
    /**
     * 增加用户和店铺
     *
     * @param param 用户和店铺的dto
     * @return 1为增加成功
     * @author 高强
     * @Date 2020年8月25日
     */
    @Override
    public int create(UmsAdminAndStoreParam param) throws ApiException{

        //把dto中的值取出放到UmsAdminParam中
        UmsAdminParam admin = paramToAdmin(param);
        //注册admin
        UmsAdmin register = adminService.register(admin);
        //把dto中的值取出放到UmsStore中
        UmsStore store = paramToStore(param);
        store.setUserId(register.getId());
        //给门店管理员授权
        UmsAdminRoleRelation umsAdminRoleRelation = new UmsAdminRoleRelation();
        umsAdminRoleRelation.setAdminId(register.getId());
        UmsRoleExample example = new UmsRoleExample();
        example.createCriteria().andNameEqualTo("门店管理员");
        List<UmsRole> umsRoles = roleMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(umsRoles)){
            umsAdminRoleRelation.setRoleId(umsRoles.get(0).getId());
            roleRelationMapper.insert(umsAdminRoleRelation);
        }
        //如果if条件满足，说明admin表数据添加成功
        if (register.getId() != null && register.getId() != 0) {
            return storeMapper.insertSelective(store);
        } else {
            return 0;
        }
    }

    /**
     * 修改店铺信息
     *
     * @param id    需要更改的店铺id
     * @param param 需要更改的店铺信息
     * @return 1为修改成功
     * @author 高强
     * @Date 2020年8月25日
     */
    @Override
    public int update(long id, UmsAdminAndStoreParam param) {
        UmsStore store = paramToStore(param);
        store.setId(id);
        int count = storeMapper.updateByPrimaryKeySelective(store);
        cacheService.delStore(id);
        UmsStore newStore = storeMapper.selectByPrimaryKey(id);
        cacheService.setStore(newStore);
        return count;
    }

    /**
     * 查询店铺信息
     *
     * @param keyword  账户名称
     * @param pageSize
     * @param pageNum
     * @return
     * @author 高强
     * @Date 2020年8月25日
     */
    @Override
    public List<UmsStore> select(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        UmsStoreExample example = new UmsStoreExample();
        UmsStoreExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andStoreNameLike("%" + keyword + "%");
            example.or(example.createCriteria().andStoreNameLike("%" + keyword + "%"));
        }
        List<UmsStore> result = new ArrayList<>();
        List<UmsStore> umsStores = storeMapper.selectByExample(example);
        if (umsStores == null && umsStores.size() == 0) {
            return result;
        } else {
            return storeMapper.selectByExample(example);
        }
    }

    /**
     * 根据id查询店铺
     *
     * @param id
     * @return
     * @author 高强
     * @Date 2020年8月25日
     */
    @Override
    public UmsStore selectByPrimaryKey(long id) {
        return storeMapper.selectByPrimaryKey(id);
    }

    @Override
    public UmsStore getStoreIdByUsername(String username) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        UmsAdmin admin = adminService.getAdminByUsername(username);
        UmsStoreExample storeExample = new UmsStoreExample();
        storeExample.createCriteria().andUserIdEqualTo(admin.getId());
        List<UmsStore> umsStores = storeMapper.selectByExample(storeExample);
        return umsStores.get(0);
    }

    @Override
    public List<UmsStoreDTO> getStoreByUsername(String username, String keyword, Integer pageSize, Integer pageNum) {
        if (pageSize == null) {
            pageSize = 5;
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        List<UmsStoreDTO> result = new ArrayList<>();
        UmsAdmin admin = adminService.getAdminByUsername(username);
        Integer adminType = admin.getAdminType();//用户权限 0超级，1省级，2店铺
        Long userId = admin.getId();//用户id
        PageHelper.startPage(pageNum, pageSize);
        List<UmsStoreDTO> umsStores = this.umsStoreDao.selectUmsStoreDTO(keyword,adminType,userId);
        if (CollectionUtils.isEmpty(umsStores)) {
            return result;
        }
        if(adminType != null && adminType.equals(2)){
            //店铺管理员
            umsStores.get(0).setAdminType(adminType);
        }
        if (umsStores != null && umsStores.size() > 0) {
            return umsStores;
        } else {
            return result;
        }
    }

    @Override
    public CommonResult setCheckInIntegration(String currentUserName, UmsCheckInIntegration umsCheckInIntegration) {
        int count = 0;
        if(umsCheckInIntegration.getStoreId() == null && umsCheckInIntegration.getId() == null){
            //新建积分设置
            UmsAdminDTO adminDTO = adminService.getAdminDTOByUserName(currentUserName);
            umsCheckInIntegration.setStoreId(adminDTO.getStoreId());
            count = checkInMapper.insertSelective(umsCheckInIntegration);
        }else{
            count = checkInMapper.updateByPrimaryKeySelective(umsCheckInIntegration);
        }
        if(count > 0){
            return CommonResult.success(count);
        }else {
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult<UmsCheckInIntegration> getCheckInIntegration(String currentUserName) {
        UmsCheckInIntegration result = new UmsCheckInIntegration();
        UmsAdminDTO adminDTO = adminService.getAdminDTOByUserName(currentUserName);
        if (adminDTO.getAdminType().equals(0) || adminDTO.getAdminType().equals(1)) {
            return CommonResult.success(result);
        }
        UmsCheckInIntegrationExample example = new UmsCheckInIntegrationExample();
        example.createCriteria().andStoreIdEqualTo(adminDTO.getStoreId());
        List<UmsCheckInIntegration> list = checkInMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(list)){
            return CommonResult.success(list.get(0));
        }else {
            return CommonResult.success(result);
        }
    }


    @Override
    public CommonPage<UmsMemberAndAgentPhone> getMyBuyer(String currentUserName, UmsMemberDto member, Integer pageSize, Integer pageNum) {
        UmsAdminDTO adminDTO = this.adminService.getAdminDTOByUserName(currentUserName);
        UmsMemberExample adminExample = new UmsMemberExample();
        UmsMemberExample.Criteria criteria = adminExample.createCriteria();
//        criteria.andTypeEqualTo(0);
        if(!StringUtils.isEmpty(member.getNickname())){
            criteria.andNicknameLike("%"+member.getNickname() + "%");
        }
        if(!StringUtils.isEmpty(member.getUsername())){
            criteria.andUsernameLike("%"+member.getUsername() + "%");
        }
        if(!StringUtils.isEmpty(member.getRealName())){
            criteria.andRealNameLike("%"+member.getRealName() + "%");
        }
        if(!StringUtils.isEmpty(member.getPhone())){
            criteria.andPhoneLike("%"+member.getPhone() + "%");
        }
        if(member.getAgentId()!=null){
            criteria.andAgentIdEqualTo(member.getAgentId());
        }
        if(adminDTO.getAdminType()==2){
            criteria.andStoreIdEqualTo(adminDTO.getStoreId());
        }
        adminExample.setOrderByClause("create_time desc");
        PageHelper.startPage(pageNum,pageSize);
        List<UmsMember> umsMembers = memberMapper.selectByExample(adminExample);
        CommonPage<UmsMember> list = CommonPage.restPage(umsMembers);
        List<UmsMember> memberList = list.getList();
        List<UmsMemberAndAgentPhone> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(memberList)) {
            for(UmsMember umsMember : memberList){
                UmsMemberAndAgentPhone ums = new UmsMemberAndAgentPhone();
                BeanUtils.copyProperties(umsMember,ums);
                if (umsMember.getAgentId() != null) {
                    UmsMember member1 = memberMapper.selectByPrimaryKey(umsMember.getAgentId());
                    ums.setAgentPhone(member1.getRealName());
                }
                result.add(ums);
            }
        }
        CommonPage<UmsMemberAndAgentPhone> page = new CommonPage<>();
        BeanUtils.copyProperties(list,page);
        page.setList(result);
        return page;
    }

    @Override
    public CommonResult<List<OrderProductStatParam>> getProductStat(String username, OrderProductStatParam param) {
        UmsAdminDTO admin = adminService.getAdminDTOByUserName(username);
        param.setStoreId(admin.getStoreId());
        List<OrderProductStatParam> result = new ArrayList<>();
        List<OrderProductStatParam> list = statDao.getList(param);
        if(list != null && list.size() > 0){
            return CommonResult.success(list);
        }else{
            return CommonResult.success(result);
        }
    }

    @Override
    public CommonResult setMemberEquity(String currentUserName, UmsStore store) {
        int count = 0;
        UmsStore umsStore = storeMapper.selectByPrimaryKey(store.getId());
        umsStore.setMemberEquity(store.getMemberEquity());
        if(store.getId() != null && store.getMemberEquity() != null) {
            count = storeMapper.updateByPrimaryKeyWithBLOBs(umsStore);
            redisService.delStore(umsStore.getId());
            redisService.setStore(umsStore);
        }
        if(count > 0){
            return CommonResult.success(count);
        }else {
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult getMemberEquity(String currentUserName) {
        UmsAdminDTO admin = adminService.getAdminDTOByUserName(currentUserName);
        UmsStore store = storeMapper.selectByPrimaryKey(admin.getStoreId());
        String memberEquity = store.getMemberEquity();
        return CommonResult.success(memberEquity);
    }


    /**
     * 把用户店家dto的部分参数转成store
     *
     * @param param
     * @return
     */
    private UmsStore paramToStore(UmsAdminAndStoreParam param) {
        UmsStore store = new UmsStore();
        store.setStoreName(param.getStoreName());
        store.setAccount(param.getAccount());
        store.setSort(param.getSort());
        store.setLevel(param.getLevel());
        store.setStatus(param.getStatus());
        store.setAuditStatus(param.getAuditStatus());
        store.setBusinessLicense(param.getBusinessLicense());
        store.setStoreAddress(param.getStoreAddress());
        store.setLinkman(param.getLinkman());
        store.setPhone(param.getPhone());
        store.setSettlementCommissionTime(param.getSettlementCommissionTime());
        store.setBusinessTime(param.getBusinessTime());
        if(!StringUtils.isEmpty(param.getLon())){
            store.setLon(new BigDecimal(param.getLon()));
        }
        if(!StringUtils.isEmpty(param.getLat())){
            store.setLat(new BigDecimal(param.getLat()));
        }
        store.setParentId(param.getParentId());
        return store;
    }

    /**
     * 把用户店家dto的部分参数转成adminParam
     *
     * @param param
     * @return
     */
    private UmsAdminParam paramToAdmin(UmsAdminAndStoreParam param) {
        UmsAdminParam admin = new UmsAdminParam();
        admin.setUsername(param.getUsername());
        admin.setPassword(param.getPassword());
        admin.setIcon(param.getIcon());
        admin.setEmail(param.getEmail());
        admin.setNickName(param.getNickName());
        admin.setNote(param.getNote());
        admin.setType(param.getType());
        return admin;
    }

}
